package com.wqtz.chechai.view.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wqtz.chechai.R;
import com.wqtz.chechai.base.BaseActivity;
import com.wqtz.chechai.presenter.BasePresent;
import com.wqtz.chechai.presenter.LoginPresenter;
import com.wqtz.chechai.utils.LogUtils;
import com.wqtz.chechai.utils.OkHttpUtils;
import com.wqtz.chechai.utils.StringUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 项目名称： CheChai
 * 创建人 :  Kisum
 * 创建时间: 2017/1/16
 */

public class SmsSetPasswordActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_Phone_number)
    TextView mTvPhoneNumber;
    @BindView(R.id.et_sms_verification)
    EditText mEtSmsVerification;
    @BindView(R.id.btn_re_send)
    TextView mBtnReSend;
    @BindView(R.id.et_set_password)
    EditText mEtSetPassword;
    @BindView(R.id.tv_password_length)
    TextView mTvPasswordLength;
    @BindView(R.id.btn_next)
    Button mBtnNext;
    private String mPhoneNumber;

    private OkHttpUtils mOkHttpUtils = OkHttpUtils.getInstance();
    private Thread mThread;
    private boolean tag = true;
    /**
     * 倒计时时间
     */
    private int i = 60;
    private String mPassword;


    @Override
    public void init() {
        Intent intent = getIntent();
        //得到上个页面的手机号
        mPhoneNumber = intent.getStringExtra("phoneNumber");
        ButterKnife.bind(this);
    }

    @Override
    public void loadData() {
        //设置当前手机号
        mTvPhoneNumber.setText("+86 " + mPhoneNumber);
        //初始化倒计时
        changeBtnGetCode();
    }

    @Override
    public int setContentViews() {
        return R.layout.activity_sms_setpassword;
    }

    @Override
    public BasePresent createPresenter() {
        return null;
    }

    /**
     * 输入验证码
     */
    public String getVerificationCode() {
        if (StringUtils.isEmpty(mEtSmsVerification.getText().toString().trim())) {
            return null;
        }
        return mEtSmsVerification.getText().toString().trim();
    }

    /**
     * 输入密码
     */
    public String getPassword() {
        if (StringUtils.isEmpty(mEtSetPassword.getText().toString().trim())) {
            return null;
        }
        return mEtSetPassword.getText().toString().trim();
    }


    @OnClick({R.id.iv_back, R.id.btn_re_send, R.id.btn_next})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_back:
                //返回获取验证码页面
                this.finish();
                break;
            //点击重发验证码
            case R.id.btn_re_send:
                //开启倒计时
                changeBtnGetCode();
                /**
                 * 重发验证码
                 */
                requestVerifyCodeAgain(mPhoneNumber);
                break;
            case R.id.btn_next:
                /**
                 * 获取验证码和密码
                 */
                String verificationCode = getVerificationCode();
                mPassword = getPassword();
                /**
                 * 验证短信验证码
                 * params : mobilePhoneNumber , smsCode
                 */
                VerifySmsCode(mPhoneNumber, verificationCode);

                break;
        }
    }

    /**
     * 重发验证码
     */
    private void requestVerifyCodeAgain(final String phoneNumber) {
        new AsyncTask<String, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(String... params) {
                //ttl后面的值是短信有效时间(分钟)
                String json = "{\"mobilePhoneNumber\":\"{0}\",\"ttl\":10,\"name\":\"注册登陆\"}";
                json = json.replace("{0}", phoneNumber);
                LogUtils.e("正在发送验证码");
                return mOkHttpUtils.postJson("https://api.leancloud.cn/1.1/requestSmsCode", json);

            }

            @Override
            protected void onPostExecute(Boolean s) {
                super.onPostExecute(s);
                if (s) {
                    LogUtils.e("验证码发送成功");
                    //验证码发送成功
                    Toast.makeText(SmsSetPasswordActivity.this, "验证码发送成功！", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(SmsSetPasswordActivity.this, "验证码发送失败！", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute(mPhoneNumber);
    }

    /**
     * 倒计时
     */
    private void changeBtnGetCode() {
        mThread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (i > 0) {
                        i--;
                        if (SmsSetPasswordActivity.this == null) {
                            break;
                        }

                        SmsSetPasswordActivity.this
                                .runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mBtnReSend.setTextColor(Color.GRAY);
                                        mBtnReSend.setText("重发验证码 "
                                                + i);
                                        mBtnReSend
                                                .setClickable(false);
                                    }
                                });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    tag = false;
                }
                i = 60;
                tag = true;
                if (SmsSetPasswordActivity.this != null) {
                    SmsSetPasswordActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBtnReSend.setTextColor(Color.rgb(175, 36, 35));
                            mBtnReSend.setText("获取验证码");
                            mBtnReSend.setClickable(true);
                        }
                    });
                }
            }

            ;
        };
        mThread.start();
    }

    /**
     * 验证短信验证码
     * params : phoneNumber , smsCode
     */
    private void VerifySmsCode(String phoneNumber, final String smsCode) {
        new AsyncTask<String, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(String... params) {
                String json = "{\"mobilePhoneNumber\":\"{0}\"}";
                json = json.replace("{0}", params[0]);
                return mOkHttpUtils.postJson("https://api.leancloud.cn/1.1/verifySmsCode/" + params[1], json);
            }

            @Override
            protected void onPostExecute(Boolean s) {
                super.onPostExecute(s);
                if (s) {
                    LogUtils.e("验证码匹配成功:" + smsCode);
                    Toast.makeText(SmsSetPasswordActivity.this, "验证码匹配成功", Toast.LENGTH_SHORT).show();
                    /**
                     * 验证密码
                     */
                    if (!StringUtils.isValidSmsPassword(mPassword)) {
                        Toast.makeText(SmsSetPasswordActivity.this, "密码只能是大于6位的字母数字下划线！", Toast.LENGTH_SHORT).show();
                    }else {
                        //跳转主页面
                        Intent intent = new Intent(SmsSetPasswordActivity.this, MainActivity.class);
                        startActivity(intent);
                        SmsSetPasswordActivity.this.finish();
                    }

                } else {
                    Toast.makeText(SmsSetPasswordActivity.this, "验证码不匹配", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute(phoneNumber, smsCode);
    }

    @Override
    protected void onResume() {
        super.onResume();
        activitys.add(this); //添加当前的activity
    }
}
